package com.xiaoying.server.publish.impl;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.xiaoying.server.publish.Handler;
import com.xiaoying.server.publish.entity.FileInfo;
import com.xiaoying.server.publish.entity.UploadResult;
import com.xiaoying.server.publish.task.UploadDealTask;
import com.xiaoying.server.publish.upload.UploadFile;

public class RequestHandler implements Handler,Runnable{
	private static Log log = LogFactory.getFactory().getInstance(RequestHandler.class);
	
	private int maxThread=10;
    private BlockingQueue<FileInfo> requestQueue;
    private BlockingQueue<UploadResult> responseQueue;
    private Executor executor;
    public AtomicInteger idleThread;
    
    @Override
    public void handle(BlockingQueue<FileInfo> reqQ,
            BlockingQueue<UploadResult> resQ) {
        this.requestQueue = reqQ;
        this.responseQueue = resQ;
        Thread proc = new Thread(this);
        proc.start();
    }

    @Override
    public void init() throws Exception {
        executor = Executors.newFixedThreadPool(maxThread);
    	idleThread = new AtomicInteger(maxThread);
    }

	@Override
    public void run() {
        while (true) {
            FileInfo fileInfo = null;
            if(this.idleThread.get()>0){
            	System.out.println("请求线程池空闲线程数量="+idleThread.get()+", 请求队列数量="+requestQueue.size());
                try {
    				fileInfo = requestQueue.take();		
                    UploadDealTask task = new UploadDealTask(requestQueue, responseQueue,fileInfo,idleThread);
                    executor.execute(task);
    			} catch (InterruptedException e) {
                    if (fileInfo != null) {
                    	requestQueue.add(fileInfo);
                    }
    			}   
            }
        }
    }

	public int getMaxThread() {
		return maxThread;
	}

	public void setMaxThread(int maxThread) {
		this.maxThread = maxThread;
	}

	
	
}
